<template>
    <div style="padding: 0 10px">
        <div class="header">
            <valuation-sel-query-condition
                @comReturn="comReturn"
                @handleButton="handleButton"
                :showSearchParams="showSearchParams"
                :isFirst="isFirst && activeValue === 'valuation-sel'"
                immediate="true"
            ></valuation-sel-query-condition>
        </div>
        <div>
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                v-table-top="page.currentPage"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                highlight-current-row
                @sort-change="changeTableSort"
                :resizable-config="{ minWidth: '60' }"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
            >
                <vxe-column type="checkbox" width="60" align="center"> </vxe-column>
                <vxe-column
                    v-for="item in showFieldList"
                    :field="item.id"
                    :title="item.content"
                    :key="item.content"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '120px'"
                    show-overflow="tooltip"
                    sortable
                >
                    <template slot-scope="scope">
                        <span v-if="['navDate'].includes(item.id)">{{ scope.row[item.id].slice(0, 10) }}</span>
                        <span v-else-if="['portCode', 'insrtTime', 'fundCode', 'fundName'].includes(item.id)">{{
                            scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--'
                        }}</span>
                        <span v-else-if="['unitNav', 'unitNavAcc'].includes(item.id)">
                            {{ numberFormat(scope.row[item.id], 4) || '--' }}
                        </span>
                        <span v-else-if="['portMatuAvg', 'portSavcAvg'].includes(item.id)">
                            {{ thousandsFormat(scope.row[item.id]) || '--' }}
                        </span>
                        <span v-else>
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>
        </div>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_VALUATION_SEL"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { downLoadFile } from '@/utils/request';
import { numberFormat, thousandsFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import ValuationSelQueryCondition from './valuation-sel-query-condition.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({ name: 'ValuationSel', components: { ValuationSelQueryCondition, RiskTableLayout, RiskPagination } })
export default class ValuationSel extends Vue {
    numberFormat = numberFormat;
    thousandsFormat = thousandsFormat;

    isOpen: boolean = false;

    showSearchParams: any = []; // 显示查询字段

    tableData: any[] = [];

    summary: any = {}; // 汇总行

    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        // fundName: 'VC_FUND_NAME',
        absAmt: 'abs_amt',
        // 资产支持证券

        accurFee: 'accur_fee',
        // 预提费用

        amorFee: 'amor_fee',
        // 待摊费用

        dprcRerv: 'dprc_rerv',
        // 减值准备

        pstnTd: 'pstn_td',
        // 今日可用头寸

        bankDpsi: 'bank_dpsi',
        // 银行存款

        bondInsmAmt: 'bond_insm_amt',
        // 其中:债券投资

        cashPct: 'cash_pct',
        // 现金类占净值比

        cdInsmAmt: 'cd_insm_amt',
        // 其中:同业存单投资

        paybClrAmt: 'payb_clr_amt',
        // 应付证券清算款

        recvClrAmt: 'recv_clr_amt',
        // 应收证券清算款

        clrAmtRmb: 'clr_amt_rmb',
        // 证券清算款-人民币

        clrRerv: 'clr_rerv',
        // 结算备付金

        credAcc: 'cred_acc',
        // 信用账户

        curDpsi: 'cur_dpsi',
        // 其中:活期存款

        depoutMarg: 'depout_marg',
        // 存出保证金

        deviAmt: 'devi_amt',
        // 偏离金额

        deviDeg: 'devi_deg',
        // 偏离度

        shdwPrcDeviDeg: 'shdw_prc_devi_deg',
        // 与影子价估值的偏离度

        astNav: 'ast_nav',
        // 基金净资产

        astShrs: 'ast_shrs',
        // 份额

        fundInsmAmt: 'fund_insm_amt',
        // 基金投资

        unitIncm: 'unit_incm',
        // 每万份基金收益

        unitNav: 'unit_nav',
        // 基金单位净值

        fwdInsm: 'fwd_insm',
        // 远期投资

        unitNavAcc: 'unit_nav_acc',
        // 累计基金单位净值

        yldAcc: 'yld_acc',
        // 累计净值增长率

        ibSellRepoFinAmt: 'ib_sell_repo_fin_amt',
        // 银行间卖出回购金融资产款

        insrtTime: 'insrt_time',
        // 插入时间

        portCode: 'port_code',
        // 主产品代码

        navDate: 'nav_date',
        // 估值日期

        odysInsm: 'odys_insm',
        // 普通股

        paybOth: 'payb_oth',
        // 其他应付款

        recvOth: 'recv_oth',
        // 其他应收款

        paidInCapi: 'paid_in_capi',
        // 实收资本

        // partNavDate: 'part_nav_date',
        // // 估值日期-分区

        paybAdviFee: 'payb_advi_fee',
        // 应付投资顾问费

        paybCstdFee: 'payb_cstd_fee',
        // 应付托管费

        paybEntrFee: 'payb_entr_fee',
        // 应付受托费

        paybIntr: 'payb_intr',
        // 应付利息

        paybMgrFee: 'payb_mgr_fee',
        // 应付管理人报酬

        paybMgrPerfRward: 'payb_mgr_perf_rward',
        // 应付管理人业绩报酬

        paybPrfit: 'payb_prfit',
        // 应付利润

        paybRedemAmt: 'payb_redem_amt',
        // 应付赎回款

        paybRedemFee: 'payb_redem_fee',
        // 应付赎回费

        paybSaleServFee: 'payb_sale_serv_fee',
        // 应付销售服务费

        paybTax: 'payb_tax',
        // 应交税费

        paybTrdFee: 'payb_trd_fee',
        // 应付交易费用

        portMatuAvg: 'port_matu_avg',
        // 投资组合平均到期日

        portSavcAvg: 'port_savc_avg',
        // 投资组合平均剩余存续期

        preStkInsmAmt: 'pre_stk_insm_amt',
        // 其中:优先股投资

        recvDivd: 'recv_divd',
        // 应收股利

        recvIntr: 'recv_intr',
        // 应收利息

        recvIntrBankDpsi: 'recv_intr_bank_dpsi',
        // 应收利息_银行存款

        recvIntrClrRerv: 'recv_intr_clr_rerv',
        // 应收利息_结算备付金

        recvIntrDepoutMarg: 'recv_intr_depout_marg',
        // 应收利息_存出保证金

        recvSubsAmt: 'recv_subs_amt',
        // 应收申购款

        relsIncm: 'rels_incm',
        // 实现收益

        rsaleFinAmt: 'rsale_fin_amt',
        // 买入返售金融资产

        sellRepoFinAmt: 'sell_repo_fin_amt',
        // 卖出回购金融资产款

        anlYld7d: 'anl_yld_7d',
        // 七日年化收益率

        realizAst7wd: 'realiz_ast_7wd',
        // 七个工作日可变现资产

        realizAst7wdPct: 'realiz_ast_7wd_pct',
        // 七个工作日可变现资产占比

        shClrMarg: 'sh_clr_marg',
        // 上海结算保证金

        shSellRepoFinAmt: 'sh_sell_repo_fin_amt',
        // 上交所卖出回购金融资产款

        shMinRerv: 'sh_min_rerv',
        // 上交所最低结算备付金

        stkInsmAmt: 'stk_insm_amt',
        // 股票投资

        spifAmt: 'spif_amt',
        // 股指期货

        spifClrRerv: 'spif_clr_rerv',
        // 清算备付金_股指期货

        spifDepoutMarg: 'spif_depout_marg',
        // 存出保证金_股指期货

        szClrMarg: 'sz_clr_marg',
        // 深圳结算保证金

        szSellRepoFinAmt: 'sz_sell_repo_fin_amt',
        // 深交所卖出回购金融资产款

        szMinRerv: 'sz_min_rerv',
        // 深交所最低结算备付金

        yldCur: 'yld_cur',
        // 本期净值增长率

        astTot: 'ast_tot',
        // 资产类合计

        libltyTot: 'liblty_tot',
        // 负债类合计

        secuInsmAmtTot: 'secu_insm_amt_tot',
        // 证券投资合计

        unitDstrIncm: 'unit_dstr_incm',
        // 单位可分配收益

        dstrIncm: 'dstr_incm',
        // 可分配收益

        yldTd: 'yld_td',
        // 今日净值增长率

        agmtDpsi: 'agmt_dpsi',
        // 协议存款

        fundCode: 'C_FUND_CODE',
        fundName: 'C_FUND_NAME',
    };

    tableColumns = [
        { id: 'navDate', content: '估值日期', minWidth: '130px', align: 'center' },
        { id: 'portCode', content: '主产品代码', align: 'left' },
        // { id: 'fundCode', content: '产品代码', align: 'left' },
        { id: 'fundName', content: '产品名称', align: 'left' },
        { id: 'astNav', content: '组合净资产', align: 'right' },
        { id: 'unitNav', content: '组合单位净值', minWidth: '150px', align: 'right' },
        { id: 'unitNavAcc', content: '累计组合单位净值', minWidth: '150px', align: 'right' },
        { id: 'yldTd', content: '今日净值增长率', minWidth: '150px', align: 'right' },
        { id: 'yldCur', content: '本期净值增长率', minWidth: '150px', align: 'right' },
        { id: 'yldAcc', content: '累计净值增长率', align: 'right' },
        { id: 'astShrs', content: '份额', align: 'right' },
        // { id: 'paidInCapi', content: '实收资本' },
        { id: 'pstnTd', content: '今日可用头寸', align: 'right' },
        { id: 'astTot', content: '资产类合计', align: 'right' },
        { id: 'libltyTot', content: '负债类合计', align: 'right' },
        { id: 'cashPct', content: '现金类占净值比', align: 'right' },
        { id: 'portMatuAvg', content: '投资组合平均到期日', align: 'right' },
        { id: 'portSavcAvg', content: '投资组合平均剩余存续期', align: 'right' },
        { id: 'anlYld7d', content: '七日年化收益率', align: 'right' },
        { id: 'unitIncm', content: '每万份基金收益', align: 'right' },
        { id: 'deviAmt', content: '偏离金额', align: 'right' },
        { id: 'deviDeg', content: '偏离度', align: 'right' },
        { id: 'shdwPrcDeviDeg', content: '与影子价估值的偏离度', align: 'right' },
        { id: 'realizAst7wd', content: '七个工作日可变现资产', align: 'right' },
        { id: 'realizAst7wdPct', content: '七个工作日可变现资产占比', align: 'right' },
        { id: 'bankDpsi', content: '银行存款', align: 'right' },
        { id: 'recvIntrBankDpsi', content: '应收利息_银行存款', align: 'right' },
        { id: 'curDpsi', content: '其中:活期存款', align: 'right' },
        { id: 'agmtDpsi', content: '协议存款', align: 'right' },
        { id: 'clrRerv', content: '结算备付金', align: 'right' },
        { id: 'recvIntrClrRerv', content: '应收利息_结算备付金', align: 'right' },
        { id: 'depoutMarg', content: '存出保证金', align: 'right' },
        { id: 'recvIntrDepoutMarg', content: '应收利息_存出保证金', align: 'right' },
        { id: 'secuInsmAmtTot', content: '证券投资合计', align: 'right' },
        { id: 'stkInsmAmt', content: '股票投资', align: 'right' },
        { id: 'preStkInsmAmt', content: '其中:优先股投资', align: 'right' },
        { id: 'odysInsm', content: '普通股', align: 'right' },
        { id: 'bondInsmAmt', content: '债券投资', align: 'right' },
        // { id: 'bondInsmAmt', content: '债券投', align: 'right' },
        { id: 'cdInsmAmt', content: '其中:同业存单投资', align: 'right' },
        { id: 'absAmt', content: '资产支持证券', align: 'right' },
        { id: 'fundInsmAmt', content: '基金投资', align: 'right' },
        { id: 'rsaleFinAmt', content: '买入返售金融资产', align: 'right' },
        { id: 'recvDivd', content: '应收股利', align: 'right' },
        { id: 'recvIntr', content: '应收利息', align: 'right' },
        { id: 'recvSubsAmt', content: '应收申购款', align: 'right' },
        { id: 'recvOth', content: '其他应收款', align: 'right' },
        { id: 'amorFee', content: '待摊费用', align: 'right' },
        { id: 'sellRepoFinAmt', content: '卖出回购金融资产款', align: 'right' },
        { id: 'shSellRepoFinAmt', content: '上交所卖出回购金融资产款', align: 'right' },
        { id: 'szSellRepoFinAmt', content: '深交所卖出回购金融资产款', align: 'right' },
        { id: 'ibSellRepoFinAmt', content: '银行间卖出回购金融资产款', align: 'right' },
        { id: 'paybRedemAmt', content: '应付赎回款', align: 'right' },
        { id: 'paybRedemFee', content: '应付赎回费', align: 'right' },
        { id: 'paybEntrFee', content: '应付受托费', align: 'right' },
        { id: 'paybAdviFee', content: '应付投资顾问费', align: 'right' },
        { id: 'paybMgrFee', content: '应付管理人报酬', align: 'right' },
        { id: 'paybCstdFee', content: '应付托管费', align: 'right' },
        { id: 'paybSaleServFee', content: '应付销售服务费', align: 'right' },
        { id: 'paybTrdFee', content: '应付交易费用', align: 'right' },
        { id: 'paybMgrPerfRward', content: '应付管理人业绩报酬', align: 'right' },
        { id: 'paybTax', content: '应交税费', align: 'right' },
        { id: 'paybIntr', content: '应付利息', align: 'right' },
        { id: 'paybPrfit', content: '应付利润', align: 'right' },
        { id: 'paybOth', content: '其他应付款', align: 'right' },
        { id: 'accurFee', content: '预提费用', align: 'right' },
        { id: 'fwdInsm', content: '远期投资', align: 'right' },
        { id: 'recvClrAmt', content: '应收证券清算款', align: 'right' },
        { id: 'paybClrAmt', content: '应付证券清算款', align: 'right' },
        { id: 'clrAmtRmb', content: '证券清算款_人民币', align: 'right' },
        { id: 'shMinRerv', content: '上交所最低结算备付金', align: 'right' },
        { id: 'szMinRerv', content: '深交所最低结算备付金', align: 'right' },
        { id: 'spifClrRerv', content: '清算备付金_股指期货', align: 'right' },
        { id: 'shClrMarg', content: '上海结算保证金', align: 'right' },
        { id: 'szClrMarg', content: '深圳结算保证金', align: 'right' },
        { id: 'spifDepoutMarg', content: '存出保证金_股指期货', align: 'right' },
        { id: 'credAcc', content: '信用账户', align: 'right' },
        { id: 'relsIncm', content: '实现收益', align: 'right' },
        { id: 'spifAmt', content: '股指期货', align: 'right' },
        { id: 'dstrIncm', content: '可分配收益', align: 'right' },
        { id: 'unitDstrIncm', content: '单位可分配收益', align: 'right' },
        { id: 'dprcRerv', content: '减值准备', align: 'right' },
        { id: 'insrtTime', content: '插入时间', align: 'center' },
    ];
    // { id: 'partNavDate', content: '估值日期-分区' },

    private page: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    private sortProp: string = 'navDate'; // 排序字段

    private sortOrder: string = 'desc'; // 排序方式

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { id: 'navDate', content: '估值日期', align: 'center' },
        { id: 'portCode', content: '主产品代码', align: 'left' },
    ];

    searchParam: any = {
        navDate: [],
        // XEUtils.toDateString(new Date(), 'yyyy-MM-dd')
        portCode: [],
        sort: 'nav_date ASC',
    }; // 查询条件

    loading: boolean = false; // 页面渲染

    tableKey: number = -1;

    isFirst: boolean = true;

    @Prop() activeValue: string;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'valuation-sel') {
            if (this.isFirst) {
                await this.queryLayout();
                this.getValuationSelTableData();
                this.isFirst = false;
            }
        }
    }

    getValuationSelTableData() {
        this.loading = true;
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/assetSelect/valuationSel', {
                    paging: {
                        currentPage: this.page.currentPage,
                        pageSize: this.page.pageSize,
                    },
                    ...this.searchParam,
                })
                .then((res: any) => {
                    if (res.total) {
                        this.summary = res.summary;
                        this.tableData = res.list;
                    } else {
                        this.summary = {};
                        this.tableData = [];
                    }
                    this.page.total = res.total;
                    this.loading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.loading = false;
                    reject(err);
                });
        });
    }

    // 查询回调
    comReturn(obj) {
        this.isOpen = obj.isOpen;
        this.searchParam = obj.searchParam;
    }

    // 分页页面返回处理
    pageRet() {
        this.getValuationSelTableData();
    }

    // 分页
    pageChange(curPage: number): void {
        this.page.currentPage = curPage;
        this.getValuationSelTableData();
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 1;
            let obj = this.tableData[0];
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
        }
        return [arr];
    }
    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.searchParam.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_VALUATION_SEL')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            this.showFieldList = this.tableColumns;
            const fixKeys = this.fixedFieldList.map(item => item.id);
            this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
                this.selectedFieldList = [];
            } else {
                this.selectedFieldList = JSON.parse(resList);
                this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            }
        }

        this.tableKey++;
    }

    // 按钮点击
    handleButton(type): void {
        if (type == 'search') {
            this.pageChange(1);
        } else if (type == 'refresh') {
            this.pageChange(1);
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        } else if (type == 'loadout') {
            let records = (this.$refs.table as any).getCheckboxRecords();
            let codes = records.map(item => item.portCode);
            console.log(codes, 'codes');

            downLoadFile({
                url: '/assetSelect/export/valuationSel',
                method: 'post',
                data: {
                    ...this.searchParam,
                    exportPortCodes: codes,
                    columns: this.showFieldList.map(item => {
                        return {
                            id: item.id,
                            content: item.content,
                        };
                    }),
                },
            });
        }
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';

/deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 265px);
    }
}
</style>
